/**
 * Created by Administrator on 2015/4/17.
 */
var Terminal = {
	LOADING_IMG : PFT_GLOBAL.CONFIG.LOADING_IMG,
	DEFAULT_IMG : PFT_GLOBAL.CONFIG.DEFAULT_IMG,
	PAYTYPE : {
		"0" : "账户余额支付",
		"1" : "支付宝支付",
		"2" : "授信支付",
		"3" : "产品自销",
		"4" : "现场支付",
		"5" : "微信支付"
	},
	ORDERSTATUS : {
		"0" : "未使用",
		"1" : "已使用",
		"2" : "已过期",
		"3" : "已取消",
		"4" : "凭证码被替代",
		"5" : "被终端撤销(已取消)",
		"6" : "被终端撤销(已使用)"
	},
	init : function(){
		var self = this;
		$("#prodListSelect").change(function(e){
			var curOptin = $(this).children("[selected=selected]");
			self.onSelectChange(curOptin);
		})
		$("#termSearBtn").on("click",function(){
			var salerId = self.getSalerid();
			var voucher = $("#termSearInp").val();
			if(!voucher) return false;
			self.getOrder({
				salerid : salerId,
				voucher : voucher
			});
			return false;
		})
		$("#termSearInp").on("keypress",function(e){
			var keyCode = e.keyCode;
			if(keyCode==13){
				var salerId = self.getSalerid();
				var voucher = $("#termSearInp").val();
				if(!voucher) return false;
				self.getOrder({
					salerid : salerId,
					voucher : voucher
				});
				return false;
			}
		})
		//验证
		$("#myOrderList").on("click",".orderItem .checkBtn",function(e){
			var btn = $(e.currentTarget);
			if(btn.hasClass("disabled") || btn.hasClass("success")) return false;
			btn.prev(".errorTip").remove();
			var data = {};
			data["check"] = 1;
			data["salerid"] = self.getSalerid();
			data["ordernum"] = btn.attr("data-mainordernum") || "";
			data["list"] = {};
			btn.prev().children().each(function(){
				var item = $(this);
				var inp = item.find(".tinp");
				var ordernum = inp.attr("data-ordernum");
				var tnum = inp.val();
				data["list"][ordernum] = tnum;
			});
			console && console.log(data);
			console && console.log(PFT_GLOBAL.U.JSON.stringify(data));
			self.terminalCheck(btn,PFT_GLOBAL.U.JSON.stringify(data));
			return false;
		})
		$("#myOrderList").on("focus",".orderItem .tinp",function(e){
			var inp = $(e.currentTarget);
			var val = inp.val();
			inp.data("lastval",val);
			return false;
		})
		$("#myOrderList").on("blur",".orderItem .tinp",function(e){
			var inp = $(e.currentTarget);
			var val = inp.val();
			var lastVal = inp.data("lastval");
			var maxNum = inp.data("maxnum");
			if(!PFT_GLOBAL.U.isPositiveNum(val)) inp.val(lastVal);
			if(val>maxNum) inp.val(lastVal);
		})
		self.onSelectChange($("#prodListSelect").find("option").first());
	},
	getSalerid : function(){
		return $("#term_prodNum").text();
	},
	onSelectChange : function(curOption){
		var id = curOption.attr("data-id");
		var terminal = curOption.attr("data-terminal");
		var salerid = curOption.attr("data-salerid");
		var src = curOption.attr("data-img");
		$("#term_prodId").text(id);
		$("#term_termNum").text(terminal);
		$("#term_prodNum").text(salerid);
		this.loadPhotoImg(id,src);
	},
	//更换产品/景区  加载photo img
	loadPhotoImg : function(id,imgpath){
		if(!imgpath) return false;
		var container = $("#prodPhoto");
		var oimg = $("#photoImg"+id);
		var img = container.children(".loading");
		$(img).attr("src",imgpath);
		if(oimg.length){
			oimg.show().siblings().hide();
		}else{
			var img = new PFT_GLOBAL.U.ImgLoador({src:imgpath});
			img.on("loading",function(){
				container.children(".loading").show().siblings().hide();
			});
			img.on("loaded",function(img){
				container.children().hide();
				img = $(img);
				img.attr("id","photoImg"+id).attr("width",container.width()).attr("height",container.height()).show().appendTo(container);
			});
			img.on("error",function(){
				container.children(".error").show().siblings().hide();
			})
			img.load();
		}
	},
	/**
	 * 根据手机号/凭证号/身份证 查询已买的订单
	 * @param opt
	 * opt参数:
	 *   salerid - 景区6位账号
	 *   voucher - 凭证码/手机号/身份证
	 */
	getOrder : function(opt){
		var self = this;
		var opt = opt || {};
		var salerid = opt.salerid;
		var voucher = opt.voucher;
		var listUl = $("#myOrderList");
		if(!salerid || !voucher){
			console && console.log("缺省salerid景区6位帐号 或 voucher凭证码/手机号/身份证");
			return false;
		}
		PFT_GLOBAL.G.Ajax({
			url : "http://www.12301.cc/call/terminal.php",
			type : "get",
			dataType : "json",
			data : {
				salerid : salerid,
				voucher : voucher
			},
			loading : function(){
				listUl.html('<li class="status loading"><img class="icon" src="'+self.LOADING_IMG+'" alt=""/><span class="t">正在查询订单...</span></li>');
			},
			removeLoading : function(){
				listUl.html("");
			},
			timeout : function(){
				listUl.html('<li class="status timeout"><span class="t">查询订单超时,请稍后重试</span></li>');
			},
			serverError : function(){
				listUl.html('<li class="status timeout"><span class="t">服务器出错,请稍后重试</span></li>');
			}
		},function(res){
			if(Object.prototype.toString.call(res) == "[object Array]" && res.length==0){
				//没有订单
				listUl.html('<li class="status empty"><span class="t">查无订单...</span></li>');
			}else{
				var html = '';
				for(var i in res){
					var d = res[i];
					var name = d["ordername"];
					var mobile = d["ordertel"];
					var paytype = d["pmode"];
					var num = d["ordernum"];
					var time = d["ordertime"];
					var begintime = d["begintime"];
					var tickets = d["tickets"];
					var status = d["status"];
					var statusTxt = "";
					var checkBtnCls = "";
					var checkBtnTxt = "验 证";
					var allow_check_when_overitme = $("#allow_check_when_overitme").val();
					var payType = d["pmode"];
					var payTypeTxt = "";
					var payTypeTip = "";
					if(status==2 || status==3){
						statusTxt = '<span class="flag overDate">'+self["ORDERSTATUS"][status]+'</span>';
						checkBtnCls = "disabled";
						if(allow_check_when_overitme==0) checkBtnTxt = self["ORDERSTATUS"][status] + "订单无法验证";
					}
					if(payType==4){
						payTypeTxt = '<span class="paytype flag">现场支付</span>';
						payTypeTip = '<p class="payTypeTip">请先确认游客已现场付费，然后给予验证</p>';
					}
					html += '<li class="orderItem">';
					html += '<div class="oTit">联系人：<span class="contactor">'+name+'</span><span class="mobile">电话：'+mobile+'</span>'+statusTxt+payTypeTxt+'</div>';
					html += '<div class="itemCon">';
					html += '<div class="ltCon">';
					html += '<p class="line"><span class="lt"><span class="vhidden">订</span>订单号：</span><span class="rt">'+num+'</span></p>';
					html += '<p class="line"><span class="lt">下单时间：</span><span class="rt">'+time+'</span></p>';
					html += '<p class="line"><span class="lt">游玩时间：</span><span class="rt">'+begintime+'</span></p>';
					html += '</div>';
					html += '<div class="inCon">';
					html += '<ul class="ticketUl">';
					for(var s in tickets){
						var t = tickets[s];
						var tname = t["name"];
						var tnum = t["tnum"];
						var torder = t["ordernum"];
						html += '<li class="ticketLi clearfix">';
						html += '<div class="inpCtrol"><input class="tinp" type="text" value="'+tnum+'" data-maxnum="'+tnum+'" data-mainordernum="'+num+'" data-ordernum="'+torder+'"/><span class="zhang">张</span></div>';
						html += '<div class="trnameCol"><p class="tname">【'+tname+'】</p><p class="bt">共<em class="tnum">'+tnum+'</em>张<i class="vt"></i>未验证<em class="tnum">'+tnum+'</em>张</p></div>';
						html += '</li>';
					}
					html += '</ul>';
					html += '<a class="checkBtn '+checkBtnCls+'" href="###" data-mainordernum="'+num+'">'+checkBtnTxt+'</a>'+payTypeTip;
					html += '</div></div></li>';
				}
				listUl.html(html);
			}
		})
	},
	terminalCheck : function(btn,data){
		if(!btn || !data) return false;
		var errorTip = "验证失败";
		PFT_GLOBAL.G.Ajax({
			url : "http://www.12301.cc/call/terminal.php",
			type : "post",
			dataType : "json",
			data : {
				data : data
			},
			loading : function(){
				btn.text("正在验证...");
			},
			removeLoading : function(){
				btn.text("验 证");
			},
			timeout : function(res){
				console && console.log("验证超时");
				var errorTip = res.msg || errorTip;
				btn.text("重新验证").before('<span class="errorTip"><i class="iconfont">&#xe654;</i> '+errorTip+'</span>');
			},
			serverError : function(res){
				console && console.log("服务器出错");
				btn.text("重新验证").before('<span class="errorTip"><i class="iconfont">&#xe654;</i> '+errorTip+'</span>');
			}
		},function(res){
			if(res && res.status && res.status=="success"){
				btn.addClass("success").html('<i class="iconfont">&#xe63f;</i><span class="t">验证成功</span>').css("padding","0 31px");
				btn.parent().children(".ticketUl").find(".tinp").attr("readonly","readonly");
			}else{
				var errorTip = res.msg || errorTip;
				btn.text("重新验证").before('<span class="errorTip"><i class="iconfont">&#xe654;</i> '+errorTip+'</span>');
			}
		})
	}
};

Terminal.init();